<template>
  <div>
    <el-dialog v-model="props.brandVisible" :title="newTitle" width="500" :before-close="handleBrandVisibleClose">
      <el-form :model="AddBrandFrom" label-width="auto" ref="AddBrandRef" label-position="top" :rules="rulesList">
        <el-form-item label="图片" prop="newImage" required>
          <ImageUpload :limit="1" v-model="AddBrandFrom.newImage" @baseUrl="handleImageList"></ImageUpload>
        </el-form-item>

        <el-form-item label="文本标签" prop="sysTagType" required>
          <el-select v-model="AddBrandFrom.sysTagType" placeholder="请选择" style="width: 100%"
            @change="handlesysTagTypeChange">
            <el-option v-for="dict in sys_tag_type" :key="dict.value" :label="dict.label" :value="dict.value"
              :disabled="disabledOptions.includes(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item :label="selectName" prop="recordValue" :required="selectName != ''" v-if="selectName">
          <el-space spacer=" ">
            <el-text>{{ menuTypeAssociationIdFrom?.name }}</el-text>
            <el-button type="primary" @click="addListId">新增</el-button>
          </el-space>
        </el-form-item>


        <el-form-item label="链接" prop="url">
          <el-input v-model.trim="AddBrandFrom.url" placeholder="请输入" :disabled="AddBrandFrom.sysTagType != 'link'">
          </el-input>
        </el-form-item>
        <el-form-item prop="titleGroups">
          <MoreLanguage :newList="AddBrandFrom.titleGroups" label="主题名称" :showRemark="true" :showControls="true">
          </MoreLanguage>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleBrandVisibleClose">取消</el-button>
          <el-button type="primary" @click="handleBrandVisibleSure(AddBrandRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <PublicList :from="menuTypeAssociationIdFrom" :newType="typeList" @publicListSure="publicListSure"
      @publicListCancel="publicListCancel" :showList="showList" :websiteId="props.websiteId"
      :languageId="props.languageId">
    </PublicList>
  </div>
</template>
<script setup scoped>
import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
import { slugify } from "transliteration";
import PublicList from "./publicList.vue";
const emits = defineEmits([
  "handleBrandVisibleClose",
  "handleBrandVisibleSure",
]);
const { proxy } = getCurrentInstance();
const { sys_tag_type } = proxy.useDict("sys_tag_type");
const disabledOptions = ["text", "article", "account", "order", "wishlist"];
const AddBrandRef = ref();
const newTitle = ref("新增"); //名称
const selectName = ref(""); //选择商品类型、文章详情、商品、品牌详情

const menuTypeAssociationIdFrom = ref({}); //公共赋值数据
const showList = ref(false)//默认不显示，列表弹出框显示
const typeList = ref('')
const siteProductSortList = ref([])//商品分类
const siteProductList = ref([])//商品
const articlesList = ref([])//文章
const brandList = ref([])//商品品牌


const AddBrandFrom = ref({
  moduleId: null,
  image: "",
  url: "",
  newImage: "",
  sysTagType: '',
  recordValue: null,//选择的id
  titleGroups: [
    // languageId:null,//语言
    // name:null,//标题
    // description:null,//描述
  ],
});

const props = defineProps({
  brandVisible: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  listItem: {
    type: Object,
    default: {},
  },
  websiteId: {
    type: String || Number,
    default: "",
  },
  moduleId: {
    type: Number,
    default: null,
  },
  languageId: {
    type: String || Number,
    default: "",
  }
});
watch(
  () => props.brandVisible,
  () => {
    if (!props.brandVisible) return;

    if (Object.keys(props.listItem).length) {
      newTitle.value = "编辑";
      getDetails();
    } else {
      getBasics();
      newTitle.value = "新增";
      proxy.resetForm("AddBrandRef");
    }
  }
);
const handleBrandVisibleSure = () => {
  proxy.$refs["AddBrandRef"].validate((valid) => {
    if (!valid) return;
    if (!proxy.publicArray(AddBrandFrom.value.titleGroups))
      return proxy.$modal.msgError("请完整填写多语言");
    AddBrandFrom.value.moduleId = props.moduleId;

    if (newTitle.value === "新增") {
      site.moduleline
        .sitewebsitemodulelineAdd({
          data: AddBrandFrom.value,
        })
        .then((res) => {
          if (res.code === 200) {
            publicReset()
            emits("handleBrandVisibleSure");
            proxy.$message.success("新增成功");
          }
        });
    } else {
      site.moduleline
        .sitewebsitemodulelineUpdate({
          pathParams: {
            id: props.listItem.id,
          },
          data: AddBrandFrom.value,
        })
        .then((res) => {
          if (res.code === 200) {
            publicReset()
            emits("handleBrandVisibleSure");
            proxy.$message.success("编辑成功");
          }
        });
    }
  });
};
const getDetails = () => {
  site.moduleline
    .sitewebsitemodulelineGetbyid({
      pathParams: {
        id: props.listItem.id,
      },
    })
    .then((res) => {
      AddBrandFrom.value.titleGroups = [];
      AddBrandFrom.value.image = res.data.image;
      AddBrandFrom.value.newImage = res.data.host;
      AddBrandFrom.value.sysTagType = res.data.sysTagType;
      handlesysTagTypeChange(res.data.sysTagType)
      detailsTree(res.data.sysTagType, Number(res.data.recordValue))
      AddBrandFrom.value.url = res.data.url
      res.data.moduleDescriptions.forEach((e) => {
        AddBrandFrom.value.titleGroups.push({
          languageId: e.languageId,
          name: e.name,
          description: e.description,
        });
      });
    });
};

const getBasics = () => {
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: Number(props.websiteId),
      },
    })
    .then((res) => {
      AddBrandFrom.value.titleGroups = [];
      res.data.languageIds.forEach((e) => {
        AddBrandFrom.value.titleGroups.push({
          languageId: e,
          name: "",
          description: "",
        });
      });
      console.log(res.data.languageIds, "[[[]]]");
    });
};
onMounted(() => {
  getList()
})
const newFrom = ref({
  pageNum: 1,
  pageSize: 999,
})
const getList = () => {
  site.general
    .sitecategoryList({
      data: {
        ...newFrom.value,
        param: {
          websiteId: Number(props.websiteId),
          languageId: Number(props.languageId),
          fatherId: 0,
        }
      },
    })
    .then((res) => {//商品分类
      siteProductSortList.value = res.data;
    });
  site.general
    .sitewebsiteproductList({
      data: {
        ...newFrom.value,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品
      siteProductList.value = res.data
      // console.log(siteProductList.value, '商品');
    });

  site.general
    .sitearticleList({
      data: {
        ...newFrom.value,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//文章
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.title
          }
        })
      }
      articlesList.value = res.data
    })

  site.general
    .sitewebsitebrandList({
      data: {
        ...newFrom.value,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品品牌
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.commonName
          }
        })
      }
      brandList.value = res.data;
      // console.log(brandList.value, '商品品牌');
    });
}

const handleBrandVisibleClose = () => {
  publicReset()
  emits("handleBrandVisibleClose");
};
const handleImageList = (list) => {
  AddBrandFrom.value.image = list.url;
};
const handlesysTagTypeChange = (val) => {
  const { elTagClass, label } = sys_tag_type.value.find(e => e.value === val)
  // console.log(elTagClass, value,val );
  AddBrandFrom.value.url = ''
  selectName.value = ''
  typeList.value = val
  AddBrandFrom.value.recordValue = null
  menuTypeAssociationIdFrom.value = {}
  if (val === 'link') return
  if (val === 'news' || val === 'brand_list') {
    AddBrandFrom.value.url = elTagClass//品牌、文章
  } else {
    selectName.value = label;
  }
  // newText.value = sys_tag_type.value.find((e) => e.value === val)?.elTagClass;
};
const publicListSure = (row) => {//确定事件，进行url处理赋值
  showList.value = false
  menuTypeAssociationIdFrom.value = row
  AddBrandFrom.value.recordValue = row.id
  changeTree(row.id)

}
const changeTree = (e) => {
  const { sysTagType } = AddBrandFrom.value
  const { elTagClass, value } = sys_tag_type.value.find(
    (e) => e.value === sysTagType
  )
  if (sysTagType === "category") {//商品分类====分类名称-c-分类id，树形结构
    const { name, id } = findNodeById(siteProductSortList.value, e)
    AddBrandFrom.value.url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "product") {//商品=== 商品名称-p-商品id
    const { name, id } = siteProductList.value.find(item => item.id === e)
    AddBrandFrom.value.url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "news_detail") {//文章详情===博客名称-n-博客id
    const { name, id } = articlesList.value.find(item => item.id === e)
    AddBrandFrom.value.url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "brand") {//品牌详情:  品牌名称-b-品牌id
    const { name, id } = brandList.value.find(item => item.id === e)
    AddBrandFrom.value.url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  }
}
const detailsTree = (sysTagType, e) => {
  if (sysTagType === "category") {//商品分类====分类名称-c-分类id，树形结构
    menuTypeAssociationIdFrom.value = findNodeById(siteProductSortList.value, e)
  } else if (sysTagType === "product") {//商品=== 商品名称-p-商品id
    menuTypeAssociationIdFrom.value = siteProductList.value.find(item => item.id === e)
  } else if (sysTagType === "news_detail") {//文章详情===博客名称-n-博客id
    menuTypeAssociationIdFrom.value = articlesList.value.find(item => item.id === e)
  } else if (sysTagType === "brand") {//品牌详情:  品牌名称-b-品牌id
    menuTypeAssociationIdFrom.value = brandList.value.find(item => item.id === e)
  }
  AddBrandFrom.value.recordValue = menuTypeAssociationIdFrom.value.id
}
function formatUrl(input) {
  return slugify(input, { separator: '-' });
}
const publicListCancel = () => {
  showList.value = false
}
const addListId = () => {
  showList.value = true
  typeList.value = AddBrandFrom.value.sysTagType
}
const findNodeById = (tree, id) => {
  for (let node of tree) {
    if (node.id === id) {
      return node; // 找到目标节点
    }
    if (node.children) {
      let found = findNodeById(node.children, id);
      if (found) return found; // 递归查找子节点
    }
  }
  return null; // 没找到
}
const publicReset = () => {
  proxy.resetForm("AddBrandRef");
  AddBrandFrom.value.titleGroups = [];
  selectName.value = "";
  menuTypeAssociationIdFrom.value = {}
}
const rulesList = {
  newImage: [{ required: true, message: "请选择", trigger: "blur" }],
  sysTagType: [{ required: true, message: "请选择", trigger: "blur" }],
  recordValue: [{ required: true, message: "请选择", trigger: "blur" }],
};
</script>